﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Configuration;
using MijnSom;

/// <summary>
/// Class for SOM SSSO
/// </summary>
public class SomSSO
{
	private String SomBrinnummer;
	private String SomBeveiligingscode;
	private String SomSsoUrl;
	private String SomWebserviceEndpoint;

	/// <summary>
	/// Gets the required SOM setting from the config
	/// </summary>
	private void getSomSettings()
	{
		try
		{
			SomBrinnummer = ConfigurationManager.AppSettings["SomBrinnummer"];
			SomBeveiligingscode = ConfigurationManager.AppSettings["SomBeveiligingscode"];
			SomSsoUrl = ConfigurationManager.AppSettings["SomLoginUrl"];
			SomWebserviceEndpoint = ConfigurationManager.AppSettings["SomWebserviceEndpoint"];
			if (SomBrinnummer == null || SomBeveiligingscode == null || SomSsoUrl == null)
			{
				OmniaLogger.Log.Error("Getting Som Settings failed.");
			}
		}
		catch (Exception ex)
		{
			OmniaLogger.Log.Error("Getting Som Settings failed, ", ex);
		}
	}

	/// <summary>
	/// Callback function for webservice SOM, just returns true
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="certificate"></param>
	/// <param name="chain"></param>
	/// <param name="sslPolicyErrors"></param>
	/// <returns></returns>
	private static bool RemoteCertificateValidationCB(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
	{
		return true;
	}

	/// <summary>
	/// Fill the required settings
	/// </summary>
	public SomSSO()
	{
		getSomSettings();
	}

   
	/// <summary>
	/// Get the Single Sign On url from SOM
	/// </summary>
	/// <param name="user"></param>
	/// <returns></returns>
	public string getSomSSOUrl(string user)
	{
		//Calling webservice SOM
		try
		{
			SingleSignOnServiceClient SsoClient = new SingleSignOnServiceClient();
			SsoClient.Endpoint.Address = new System.ServiceModel.EndpointAddress(SomWebserviceEndpoint);
			System.Net.ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCB;
			PortalLoginLink[] SomResponses = SsoClient.aanmeldenGebruikerBeveiligingsCode(SomBrinnummer, user, SomBeveiligingscode);

			foreach (PortalLoginLink SomResponse in SomResponses)
			{
				if (SomResponse.url == "error")
				{
					OmniaLogger.Log.Error("Single Sign On failed for: " + user + ", " + SomResponse.beschrijving);
				}
				else
				{
					SomSsoUrl = SomResponse.url;
					OmniaLogger.Log.Error("Som Single Sign On url for: " + user + " is " + SomResponse.url);
				}
			}
			return SomSsoUrl;
		}
		catch (Exception ex)
		{
			OmniaLogger.Log.Error("Callng webservice SOM failed: ", ex);
			return null;
		}
	}

 
}